﻿using Newtonsoft.Json;
using PidKeyReptile.Desktop.Helper;
using PidKeyReptile.Desktop.Model;
using PidKeyReptile.Desktop.Pages.Checker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PidKeyReptile.Desktop
{
    //任务体
    public class BoundObject : GetWeb
    {
        public Queue<GatherKey> gathers;
        public CheckerManagerViewModel _checker;

        public BoundObject(CheckerManagerViewModel Checker)
        {
            _checker = Checker;
            gathers = new Queue<GatherKey>();
        }

        //检测结果
        public void Result(int id, ChekerKeyResult res)
        {
            var resul = res.result.ToString();
            if (res.state == "done")
            {

                try
                {
                    var keyDetails = JsonConvert.DeserializeObject<KeyDetails[]>(resul)[0];

                    Db.Updateable<GatherKey>()
                        .SetColumns(it => new GatherKey
                        {
                            Description = keyDetails.prd,
                            SkuId = keyDetails.eid,
                            IsKeyType = keyDetails.is_key_type,
                            IsRetail = keyDetails.is_retail,
                            ActivCount = keyDetails.remaining,
                            Blocked = keyDetails.blocked,
                            ErrorCode = keyDetails.errorcode,
                            SubType = keyDetails.sub,
                            UpTime = DateTime.Now,
                        }).Where(it => it.Id == id).ExecuteCommand();
                }
                catch (Exception ex)
                {

                    Db.Updateable<GatherKey>().SetColumns(it => new GatherKey() { ActivCount = -1, UpTime = DateTime.Now }).Where(it => it.Id == id).ExecuteCommand();

                }
            }
            else
            {
                if (resul.Contains("24h!"))
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        _checker.windowManager.ShowMessageBox($"暂停任务，任务{_checker.SelectTaskTabs.Name}得更换IP了");
                    });
                    _checker.PauseTask();
                }

            }
        }

        /// <summary>
        /// 检测秘钥
        /// </summary>
        /// <returns></returns>
        public GatherKey Detection()
        {
            if (gathers.Count == 0)
            {
                push();
            }
            var gather = gathers.Dequeue();
            return gather;
        }

        //入栈
        private void push()
        {
            var res = Db.Queryable<GatherKey>().Where(it => it.ActivCount >= 0).OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).ToList();
            foreach (var item in res)
            {
                gathers.Enqueue(item);
            }
        }
    }
}
